package biz.datalk.industrialland.common.shiro;

import org.apache.shiro.web.servlet.SimpleCookie;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author tarofang@163.com
 * @date 2022-07-15
 */
public class CustomSimpleCookie extends SimpleCookie {
    private static final Logger log = LoggerFactory.getLogger(CustomSimpleCookie.class);

    public static final String SIMPLE_COOKIE_NAME = "XTRM";

    private boolean shiroUseRememberMe;

    public CustomSimpleCookie() {
        super(SIMPLE_COOKIE_NAME);
    }

    public CustomSimpleCookie(boolean shiroUseRememberMe) {
        this();
        this.shiroUseRememberMe = shiroUseRememberMe;
    }

    public CustomSimpleCookie(String name, boolean shiroUseRememberMe) {
        super(name);
        this.shiroUseRememberMe = shiroUseRememberMe;
    }

    @Override
    public void saveTo(HttpServletRequest request, HttpServletResponse response) {
        if (shiroUseRememberMe) {
            if (log.isTraceEnabled()) {
                log.trace("CustomSimpleCookie.saveTo use super.");
            }
            super.saveTo(request, response);
        }
        // nothing to do
        if (log.isTraceEnabled()) {
            log.trace("CustomSimpleCookie.saveTo nothing to do.");
        }
    }

    @Override
    public void removeFrom(HttpServletRequest request, HttpServletResponse response) {
        if (shiroUseRememberMe) {
            if (log.isTraceEnabled()) {
                log.trace("CustomSimpleCookie.removeFrom use super.");
            }
            super.removeFrom(request, response);
        }
        // nothing to do
        if (log.isTraceEnabled()) {
            log.trace("CustomSimpleCookie.removeFrom nothing to do.");
        }
    }

    @Override
    public String readValue(HttpServletRequest request, HttpServletResponse ignored) {
        if (shiroUseRememberMe) {
            if (log.isTraceEnabled()) {
                log.trace("CustomSimpleCookie.readValue use super.");
            }
            return super.readValue(request, ignored);
        }
        // nothing to do
        if (log.isTraceEnabled()) {
            log.trace("CustomSimpleCookie.readValue nothing to do.");
        }
        return null;

    }
}
